package n206;

import javax.print.attribute.HashDocAttributeSet;

/**
 * @author 苏文广
 * @since 2021/9/29
 */
public class Solution2 {

    // 遍历: 将后一个节点指向前一个节点, 保存前一个节点
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4, new ListNode(5, null)))));


        ListNode listNode1 = reverseList(listNode);
        System.out.println(listNode1);
    }

    public static ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode next;

        while (head != null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        return pre;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
